<template>
	<view class="container">
		<uni-forms ref="form" :modelValue="formData" :rules="formRules" class="form">
			<uni-forms-item label="服务器IP" required>
				<uni-easyinput v-model="formData.ip" placeholder="请输入服务器IP地址" />
			</uni-forms-item>
			<uni-forms-item label="服务端口" required>
				<uni-easyinput v-model="formData.port" placeholder="请输入服务端口号" />
			</uni-forms-item>
			<uni-forms-item label="启用SSL" class="form-item" required>
				<view v-else>
					<switch :checked="formData.ssl == 'Y'" @change="switchSslChange" />
				</view>
			</uni-forms-item>
		</uni-forms>
		<button type="primary" @click="submit('form')">保存</button>	
	</view>
</template>


<script>
	export default {
		data() {
			return {
				// 基础表单数据
				formData: {
					ip: null,
					port: null,
					ssl: 'N'
				},
				// 校验规则
				flowRules: {
					ip: {
						rules: [{
							required: true,
							errorMessage: 'IP地址不能为空'
						}]
					},
					port: {
						rules: [{
							required: true,
							errorMessage: '服务端口不能为空'
						}]
					}
				},
			}
		},
		onLoad() {
			uni.getStorage({
				key: 'server',
				success: function (res) {
					console.log(res.data);
				}
			});
		},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			this.$refs.form.setRules(this.flowRules)
		},
		
		methods: {
			switchSslChange(e) {
				this.formData.ssl = e.detail.value ? 'Y':'N';
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					uni.setStorage({
						key: 'server',
						data: this.formData,
						success: function () {
						this.$modal.showToast('保存成功');
							this.$tab.navigateBack();	
						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style>
	.form {
		padding: 15px;
		background-color: #fff;
	}
	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>